package cn.smvc.wechat.test.dao.impl;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.smvc.common.dao.JDBCUtils;
import cn.smvc.wechat.test.dao.WeChatUserDao;
import cn.smvc.wechat.test.entity.WeChatUser;

public class WeChatUserDaoImpl implements WeChatUserDao {

	@Override
	public int save(WeChatUser weChatUser) {
		// 添加用户的sql
		String sql = "insert into wechat_user values(null,?,?,?,?,?,?,?,?) ";
		// 用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		int result = 0;
		try {
			// 用queryRunner保存用户信息
			result = queryRunner.update(sql, 
					weChatUser.getToUserName(),
					weChatUser.getFromUserName(),
					weChatUser.getLastContentTime(),
					weChatUser.getTel(),
					weChatUser.getWechatName(),
					weChatUser.getWechatNo(),
					weChatUser.getRealName(),
					weChatUser.getDelFlag());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public WeChatUser getByToUserNameAndFromUserName(String toUserName, String fromUserName) {
		String sql = "select * from wechat_user where toUserName=? and fromUserName=? and delFlag=?";
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		WeChatUser user = null;
		try {
			user = queryRunner.query(sql, 
					new BeanHandler<WeChatUser>(WeChatUser.class), 
					toUserName, 
					fromUserName, 
					0);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public int update(WeChatUser weChatUser) {
		// 添加用户的sql
		String sql = "update wechat_user set toUserName=?, "
				+ "fromUserName=?, "
				+ "lastContentTime=?, "
				+ "tel=?, "
				+ "wechatName=?, "
				+ "wechatNo=?, "
				+ "realName=?, "
				+ "delFlag=? "
				+ "where id=?";
		// 用JDBCUtils工具创建一个queryRunner对象
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		int result = 0;
		try {
			// 用queryRunner保存用户信息
			result = queryRunner.update(sql, 
					weChatUser.getToUserName(),
					weChatUser.getFromUserName(),
					weChatUser.getLastContentTime(),
					weChatUser.getTel(),
					weChatUser.getWechatName(),
					weChatUser.getWechatNo(),
					weChatUser.getRealName(),
					weChatUser.getDelFlag(), 
					weChatUser.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
